import os
import pcap
import dpkt
import socket
import urllib

from struct import unpack,pack

URL_Malware_DNS = "https://nsgbot.googlecode.com/svn/wiki/Malware_DNS.wiki"

http_fd = "/tmp/nsgbot_httpQ"

SIZE_OF_PPKT = 168
TAG_GET = 3000001
TAG_POST = 3000002

def read_db(url):
    file = urllib.urlopen(url)
    for index in file:
        temp = index.split("||")
        # check number of elements
        if len(temp) != 7:
            print "Error"
            continue
        # get element
        DNS_DIC[temp[2]] = temp[3]
        print temp[2], temp[3]

def read_pipe():
    pipein = open(http_fd, 'r')
    while 1:
        line = pipein.read(SIZE_OF_PPKT)
        parse_ppkt(line)

def parse_ppkt(ppkt):
    tv_sec = unpack('Q', ppkt[0:8])[0]
    tv_usec = unpack('Q', ppkt[8:16])[0]
    saddr = pcap.ntoa(unpack('i',ppkt[16:20])[0])
    daddr = pcap.ntoa(unpack('i',ppkt[20:24])[0])
    proto = unpack('H',ppkt[24:26])[0]
    sport = unpack('H',ppkt[26:28])[0]
    dport = unpack('H',ppkt[28:30])[0]

    # get payload size
    payload_size = unpack('H',ppkt[160:162])[0]
    payload = ppkt[30:30+payload_size]
    tag = unpack('I',ppkt[164:168])[0]

    # parse http
    request = get_url(tag, payload)
    print saddr, daddr, dport, tag, request

def get_url(tag, payload):
    # payload is Layer 7 data
    # start from GET message
    if tag == TAG_GET:
        # GET
        temp = payload.split(" ")
        return temp[1]

    elif tag == TAG_POST:
        # POST
        temp = payload.split(" ")
        return temp[1]

#read_db(URL_Malware_DNS)
read_pipe()
